package com.dnzx.controller.web;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.dnzx.framework.result.ResultUtils;
import org.dnzx.framework.result.domain.Result;
import org.dnzx.util.PropertyUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>附件上传工具类</p>
 * @Package com.dnzx.base.controller.attachment
 * @author Steven
 * @e-mail zsq.471214943@163.com
 * @date 2018-07-25 11:57:30
 * @version V1.0
 */

@RestController
@RequestMapping("/web/common")
@Api(value = "/web/common",description = "附件上传",produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public class WebCommonController {

    @PostMapping("/fileUpload")
	@ApiOperation(value="/fileUpload",notes="上传文件（图片和其他格式都可以）",httpMethod="POST",produces=MediaType.APPLICATION_JSON_VALUE)
    public Result fileUpload(MultipartFile uploadFile, HttpServletRequest request) {
        String fileUri = null;
        try {
        	if (null != uploadFile) {
                // 服务器上保存文件的目录
                String pathRoot = PropertyUtil.getProperty("file.path");
                // 获取上传文件的原文件名
                String fileName = uploadFile.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                String nextPath = fileType;
                String savePath = pathRoot + nextPath;
                String filePath = nextPath + "/" + newFileName;
                File fileDir = new File(savePath);
                // 如果目录不存在，新建文件目录
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                // 将最终的上传绝对目录返回
                uploadFile.transferTo(new File(savePath, newFileName)); // 上传文件
                fileUri = PropertyUtil.getProperty("file.uri") + filePath;// 返回文件URL
            }
            return ResultUtils.returnSuccess("SUCCESS", fileUri);
        } catch (Exception e) {
            return ResultUtils.returnError(e.getMessage());
        }

    }
}
